const { ipcMain, BrowserWindow } = require('electron')

const getSource = (url) => {
  return new Promise((resolve,reject)=> {
    console.log(url);  //控制台打印
    const win = new BrowserWindow({
      width: 500,
      height: 500,
      show: false,  //是否显示窗口
      webPreferences: {
        offscreen: true, //内存
      }
    })

    win.loadURL(url)
    win.webContents.on('did-finish-load', async ()=>{  //界面渲染完，执行函数
      let title = win.getTitle()  //获取主题
      try {
        let image = await win.webContents.capturePage() //截取内容图片，返回nativeImage
        let screenshot = image.toDataURL() //转为base64

        if( image.isEmpty() ){
          resolve({
            msg: '无法访问！'
          })
        }else {
          resolve({
            title,
            screenshot,
            url
          })
        }
        
      } catch (error) {
        reject(error)
      }
    })
  })
}

ipcMain.handle('on-url-event', async (e, url)=> {
    return await getSource(url)
})